package com.sz.biz.common.customer.service.impl;

import com.sz.biz.common.base.dto.AreaDto;
import com.sz.biz.common.base.dto.CurrencyDto;
import com.sz.biz.common.base.entity.SettlementType;
import com.sz.biz.common.base.service.AreaService;
import com.sz.biz.common.base.service.CurrencyService;
import com.sz.biz.common.base.service.SettlementTypeService;
import com.sz.biz.common.constants.CustomerConstants;
import com.sz.biz.common.constants.ErrorCodes;
import com.sz.biz.common.constants.ModuleNames;
import com.sz.biz.common.customer.dto.*;
import com.sz.biz.common.customer.entity.CusCustomer;
import com.sz.biz.common.customer.entity.CusUser;
import com.sz.biz.common.customer.service.CustomerCompanyService;
import com.sz.biz.common.customer.service.CustomerService;
import com.sz.biz.common.customer.service.CustomerUserService;
import com.sz.biz.common.platform.entity.PlatformCompany;
import com.sz.biz.common.platform.service.PlatformCompanyService;
import com.sz.biz.common.utils.NOGenerator;
import com.sz.biz.common.utils.PassWordCreate;
import com.sz.biz.logistics.core.service.PriceComboService;
import com.sz.biz.pay.account.entity.Account;
import com.sz.biz.pay.account.entity.ThirdPayAccount;
import com.sz.biz.pay.account.service.AccountService;
import com.sz.biz.pay.account.service.ThirdPayAccountService;
import com.sz.biz.pay.constants.PayConstant;
import com.sz.common.base.constants.UserActions;
import com.sz.common.base.dao.ParamData;
import com.sz.common.base.dto.QResultDto;
import com.sz.common.base.dto.QueryParams;
import com.sz.common.base.exception.Exceptions;
import com.sz.common.base.service.AbstractService;
import com.sz.common.base.utils.CheckDataUtils;
import com.sz.common.base.utils.CredentialUtils;
import com.sz.common.base.utils.StringUtils;
import com.sz.common.base.utils.UUIDGenerator;
import com.sz.common.core.service.PrincipalLogUtils;
import com.sz.common.core.service.PrincipalUtils;
import com.sz.common.core.system.dto.FileInfoDto;
import com.sz.common.core.system.dto.UserDto;
import com.sz.common.core.system.service.SysDictService;
import com.sz.common.core.system.service.SysFileGroupService;
import com.sz.common.core.system.service.UserService;
import com.sz.common.pay.pingan.constant.CertificateType;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.*;

/**
 * Created by xutao on 17/4/6.
 */
@Service("CustomerService")
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class CustomerServiceImpl extends AbstractService implements CustomerService {

    private static final String SUP_ = "sup_";
    @Autowired
    CustomerUserService customerUserService;

    @Autowired
    SysDictService sysDictService;

    @Autowired
    PriceComboService priceComboService;

    @Autowired
    SettlementTypeService settlementTypeService;

    @Autowired
    CurrencyService currencyService;

    @Autowired
    UserService userService;

    @Autowired
    SysFileGroupService fileGroupService;

    @Autowired
    AreaService areaService;

    @Autowired
    PlatformCompanyService platformCompanyService;

    @Autowired
    CustomerCompanyService customerCompanyService;

    @Autowired
    AccountService accountService;

    @Autowired
    ThirdPayAccountService thirdPayAccountService;

    private static final String SEPARATOR = "，";


    /**
     * 贸易获取客户信息， 返回id， username， code
     * @param customerCodes
     * @return
     */
    @Override
    public List<CusCustomerTradeDto> findCustomerTrade(List<String> customerCodes){
        ParamData paramData = new ParamData();
        paramData.put("customerCodes", customerCodes);
        return dao.findForList(getSqlName("findCustomerTrade"), paramData, CusCustomerTradeDto.class);
    }

    @Override
    public QResultDto findNameCodeDtoForLogistic(String q, int pageIndex, int pageSize) {

        ParamData pd = this.convertQueryParams(new QueryParams(pageSize, pageIndex, q, null, false, null));

        List<CustomerCodeNameDto> list = dao.findForList(getSqlName("findNameCodeDtoForLogisticListPage"),pd,CustomerCodeNameDto.class);

        QResultDto qResultDto = new QResultDto();
        qResultDto.setData(list);
        qResultDto.setPagination(pd.getPagination());

        return qResultDto;
    }

    @Override
    public QResultDto findNameCodeDtoForTrade(String q, int pageIndex, int pageSize) {

        ParamData pd = this.convertQueryParams(new QueryParams(pageSize, pageIndex, q, null, false, null));

        List<CustomerCodeNameDto> list = dao.findForList(getSqlName("findNameCodeDtoForTradeListPage"),pd,CustomerCodeNameDto.class);

        QResultDto qResultDto = new QResultDto();
        qResultDto.setData(list);
        qResultDto.setPagination(pd.getPagination());

        return qResultDto;
    }

    @Override
    public int save(CusCustomer entry) {
        checkDataValid(entry);

        UserDto userDto = userService.findUserDetailByUserId(PrincipalUtils.getAccountId());
        if (userDto != null) {
            entry.setCreator(userDto.getFullName() + " " + userDto.getUserName());
        }
        else {
            entry.setCreator(PrincipalUtils.getAccountName());
        }
        entry.setCreatorId(PrincipalUtils.getAccountId());
        entry.setLocked(true);
        if (entry.getUserType() == CustomerConstants.Type.CUSTOMER  &&
                entry.getCode() != null &&
                entry.getCode().startsWith(SUP_)) {
            entry.setUserType(256);
        }
        dao.save(getSqlName("insertSelective"), entry);

        Map<String, Object> dataBackup = new HashMap<>();
        dataBackup.put("ADD_CUSTOMER", entry.getId());
        PrincipalLogUtils.addOperationLog(ModuleNames.CUS, ModuleNames.CUS_CUSTOMER, UserActions.ADD, "新增客户", dataBackup);

        CusUser cusUser = new CusUser();
        cusUser.setRefCustomerId(entry.getId());
        if (entry.getUserType() == 256 && entry.getCode() != null && entry.getCode().startsWith(SUP_)) {
            cusUser.setUserName(entry.getCode().substring(4));
        } else {
            cusUser.setUserName(entry.getCode());
        }
        cusUser.setFullName("customer");
        cusUser.setIsSystem(true);
        cusUser.setMobilePhone("-");
        cusUser.setEmail(entry.getEmail());
        PassWordCreate pwc = new PassWordCreate();
        String pswd = pwc.createPassWord(6);
        cusUser.setPassword(pswd);
        cusUser.setIsLocked(true);
        cusUser.setNeedResetPwd(true);
        //关联插入一条子账号信息
        customerUserService.save(cusUser);
        dataBackup = new HashMap<>();
        dataBackup.put("ADD_CUSTOMER_USER", cusUser.getId());
        PrincipalLogUtils.addOperationLog(ModuleNames.CUS, ModuleNames.CUS_CUSTOMER, UserActions.ADD, "关联新增客户子账户", dataBackup);
        return entry.getId();
    }

    @Override
    public void batchDelete(List<Integer> ids) {

        dao.delete(getSqlName("logicDeleteByIds"), ids);

        dao.delete("CusUserMapper.logicDeleteByCustomerIds", ids);

        dao.delete("CusCustomerContactsMapper.logicDeleteByCustomerIds", ids);

        dao.delete("CusCompanyMapper.logicDeleteByCustomerIds", ids);

        dao.delete("CusBusinessContactsMapper.logicDeleteByCustomerIds", ids);

        Map<String, Object> dataBackup = new HashMap<>();
        dataBackup.put("DELETE_CUSTOMER", ids);
        PrincipalLogUtils.addOperationLog(ModuleNames.CUS, ModuleNames.CUS_CUSTOMER, UserActions.DELETE, "删除客户", dataBackup);
    }

    @Override
    public void update(List<CusCustomer> cusCustomerList) {
        if (cusCustomerList != null) {
            for (int i = 0; i < cusCustomerList.size(); i++) {
                checkDataValidForUpdate(cusCustomerList.get(i));
                CusCustomer newCustomer = cusCustomerList.get(i);
                CusCustomer cusCustomer = findSimpleById(cusCustomerList.get(i).getId());
                if (cusCustomer != null && cusCustomer.getUserType() != null && !cusCustomer.getUserType().equals(newCustomer.getUserType())) {
                    updateUserType(cusCustomer.getId(), newCustomer.getUserType());
                    return;
                }

                CusCompanyDto cusCompany = customerCompanyService.findCompanyByCustomerId(cusCustomerList.get(i).getId());
                if (checkCompangyInfoAndSetCustomerAuthStatus(cusCompany)) {
                    if (cusCustomer.getAuthStatus() == null || cusCustomer.getAuthStatus()< 1) {
                        cusCustomerList.get(i).setAuthStatus(1);
                        createPayAccount(cusCustomer,cusCompany);
                    }
                } else {
                    if (cusCustomer.getAuthStatus() == null || cusCustomer.getAuthStatus() != 0) {
                        cusCustomerList.get(i).setAuthStatus(0);
                    }
                }
            }
            dao.batchUpdate(getSqlName("updateByIds"), cusCustomerList);
            Map<String, Object> dataBackup = new HashMap<>();
            dataBackup.put("UPDATE_CUSTOMER", cusCustomerList);
            PrincipalLogUtils.addOperationLog(ModuleNames.CUS, ModuleNames.CUS_CUSTOMER, UserActions.UPDATE, "更新客户", dataBackup);
        }
    }
    private void updateUserType(int customerId,int userType){
            ParamData pd = new ParamData();
            pd.put("id", customerId);
            pd.put("userType", userType);
            dao.update(getSqlName("updateUserType"), pd);
    }

    private  boolean checkCompangyInfoAndSetCustomerAuthStatus(CusCompanyDto cusCompany){
        if (cusCompany != null) {
            if (StringUtils.isEmpty(cusCompany.getFullName())) {
                return false;
            }
            if (StringUtils.isEmpty(cusCompany.getLocationCountryCode())) {
                return false;
            }
            if (StringUtils.isEmpty(cusCompany.getLocationCityCode())) {
                return false;
            }
            if (StringUtils.isEmpty(cusCompany.getResidence())) {
                return false;
            }
            if (StringUtils.isEmpty(cusCompany.getLegalPerson())) {
                return false;
            }
            if (StringUtils.isEmpty(cusCompany.getTaxCode())) {
                return false;
            }
            if (StringUtils.isEmpty(cusCompany.getDepositBank())) {
                return false;
            }
            if (StringUtils.isEmpty(cusCompany.getBankAccountNo())) {
                return false;
            }
            if (StringUtils.isEmpty(cusCompany.getTelNo())) {
                return false;
            }
        }
        else {
            return false;
        }
        return true;
    }



    @Override
    public QResultDto find(String q, String sortName, boolean isAsc, int pageIndex, int pageSize, String refCombos,
                           Integer isLocked, int evaluateLeval, boolean beyondLeval, boolean advancedSeach,
                           Integer userType) {
        List<Integer> userTypes  = getUserTypes(userType);
        Map<String, Object> map = new HashMap<>();
        map.put("refCombos", refCombos);
        map.put("isLocked", isLocked);
        map.put("evaluateLeval", evaluateLeval);
        map.put("beyondLeval", beyondLeval);
        map.put("advancedSeach", advancedSeach);
        map.put("userTypes", userTypes);

        ParamData pd = this.convertQueryParams(new QueryParams(pageSize, pageIndex, q, sortName, isAsc, null).put(map));
        List<CusDto> qurReslist = dao.findForList(getSqlName("findByParamListPage"), pd, CusDto.class);

        for (int i = 0; i < qurReslist.size(); i++) {
            String businessTypeName = businessType2Name(qurReslist.get(i).getBusinessType(),qurReslist.get(i).getUserType());
            qurReslist.get(i).setBusinessTypeValue(businessTypeName);
            String comboName = priceComboService.findNameByCode(qurReslist.get(i).getRefCombos());
            qurReslist.get(i).setCombosName(comboName);
        }
        QResultDto qResultDto = new QResultDto();
        qResultDto.setData(qurReslist);
        qResultDto.setPagination(pd.getPagination());

        return qResultDto;
    }

    private List<Integer> getUserTypes(Integer userType) {
        List<Integer> userTypes;
        if (userType == null) {
            userType = 1;
        }
        switch (userType){
            case 1:
                userTypes = Arrays.asList(1,3);
                break;
            case 2:
                userTypes = Arrays.asList(2,3,256);
                break;
            default:
                userTypes= Arrays.asList(1);
        }
        return userTypes;
    }

    /**
     * 获取客户列表,返回id， userName, code
     * @param q
     * @param sortName
     * @param isAsc
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @Override
    public QResultDto findShort(String q, String sortName, boolean isAsc, int pageIndex, int pageSize,
                                Integer userType) {

        if (userType == null || userType < 1) {

            userType = 1;
        }

        QueryParams queryParams = new QueryParams(pageSize, pageIndex, q, sortName, isAsc, null);
        queryParams.put("userType", userType);

        ParamData pd = this.convertQueryParams(queryParams);
        List<CusShortDto> qurReslist = dao.findForList(getSqlName("findCustomersListPage"), pd, CusShortDto.class);
        QResultDto qResultDto = new QResultDto();
        qResultDto.setData(qurReslist);
        qResultDto.setPagination(pd.getPagination());

        return qResultDto;
    }

    /**
     * 商品企业限制
     * @param q
     * @param supplierCode
     * @param sortName
     * @param isAsc
     * @param pageIndex
     * @param pageSize
     * @param userType
     * @return
     */
    @Override
    public QResultDto findShortForGoods(String q, String supplierCode, String sortName, boolean isAsc, int pageIndex, int pageSize, Integer userType){
        if (userType == null || userType < 1) {
            userType = 1;
        }
        QueryParams queryParams = new QueryParams(pageSize, pageIndex, q, sortName, isAsc, null);
        queryParams.put("userType", userType);

        ParamData pd = this.convertQueryParams(queryParams);
        if(!StringUtils.isEmpty(supplierCode)){
            pd.put("isPlatform", false);
            PlatformCompany platformCompany = platformCompanyService.findByCode(supplierCode);
            if(null != platformCompany){
                pd.put("isPlatform", true);
            }
        }
        List<CusShortDto> qurReslist = dao.findForList(getSqlName("goodsCustomersListPage"), pd, CusShortDto.class);
        QResultDto qResultDto = new QResultDto();
        qResultDto.setData(qurReslist);
        qResultDto.setPagination(pd.getPagination());

        return qResultDto;
    }

    @Override
    public int checkCustomerAuthStatus(int refCustomerId) {
        CusCustomer cusCustomer = findSimpleById(refCustomerId);
        if (cusCustomer != null) {
            if (cusCustomer.getAuthStatus() != null ) {
                return cusCustomer.getAuthStatus();
            }
        }
        return 0;
    }

    @Override
    public void lockCustomer(List<Integer> ids) {
        if (ids != null && ids.size() > 0) {
            dao.update(getSqlName("lockCustomerByIds"), ids);
        }
        Map<String, Object> dataBackup = new HashMap<>();
        dataBackup.put("LOCK_CUSTOMER", ids);
        PrincipalLogUtils.addOperationLog(ModuleNames.CUS, ModuleNames.CUS_CUSTOMER, UserActions.LOCK, "锁定客户", dataBackup);
    }

    @Override
    public void unlockCustomer(List<Integer> ids) {
        if (ids != null && ids.size() > 0) {
            dao.update(getSqlName("unlockCustomerByIds"), ids);
        }
        Map<String, Object> dataBackup = new HashMap<>();
        dataBackup.put("UNLOCK_CUSTOMER", ids);
        PrincipalLogUtils.addOperationLog(ModuleNames.CUS, ModuleNames.CUS_CUSTOMER, UserActions.UNLOCK, "解锁客户", dataBackup);
    }

    @Override
    public CusCustomer  findSimpleById(Integer id) {
        CusCustomer customer = (CusCustomer) dao.findForObject(getSqlName("selectByPrimaryKey"), id);

        if (ObjectUtils.isEmpty(customer)) {
            return null;
        }

        return customer;
    }
    @Override
    public CusCustomerDto findById(Integer id) {

        CusCustomer customer = (CusCustomer) dao.findForObject(getSqlName("selectByPrimaryKey"), id);

        if (ObjectUtils.isEmpty(customer)) {
            return null;
        }

        CusCustomerDto cusCustomerDto = new CusCustomerDto();
        BeanUtils.copyProperties(customer, cusCustomerDto);

        String comboName = priceComboService.findNameByCode(customer.getRefCombos());
        cusCustomerDto.setCombosName(comboName);

        SettlementType settlementType = settlementTypeService.findById(customer.getRefSettlementId());
        cusCustomerDto.setSettlementName(settlementType == null ? "" : settlementType.getName());
        cusCustomerDto.setSettlementCode(settlementType == null ? "" : settlementType.getCode());
        CurrencyDto currencyDto = currencyService.findSingleCurencyByCode(customer.getTradingCurrency());
        cusCustomerDto.setCurrencyName(currencyDto == null ? "" : currencyDto.getName());
        if (customer.getCreatorId() == null || customer.getCreatorId() == 0) {
            cusCustomerDto.setFullName(customer.getCode());
        } else {

            UserDto userDto = userService.findUserDetailByUserId(customer.getCreatorId());
            cusCustomerDto.setFullName(userDto == null ? "" : userDto.getFullName());
        }
        return cusCustomerDto;
    }

    @Override
    public Boolean checkCodeExist(String code) {
        CusCustomer customerExist = (CusCustomer) dao.findForObject(getSqlName("findByCode"), code);
        return customerExist != null;
    }

    @Override
    public List<CusCustomer> findShortByIds(List<Integer> customerIdList) {
        List<CusCustomer> customerList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(customerIdList)) {
            ParamData pd = new ParamData();
            pd.put("ids", customerIdList);
            customerList = dao.findForList(getSqlName("findShortByIds"), pd, CusCustomer.class);
        }

        return customerList;

    }

    @Override
    public CusCustomer findShortById(Integer customerId) {
        CusCustomer cusCustomer = null;
        List<CusCustomer> customerList = this.findShortByIds(Arrays.asList(customerId));
        if (!CollectionUtils.isEmpty(customerList)) {
            cusCustomer = customerList.get(0);
        }
        return cusCustomer;
    }

    @Override
    public Map<String,Object> registerEnterpriseAccount(String userName, String code, String telNo, String password) {

        if (StringUtils.isEmpty(userName)) {
            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "企业名");
        }
        if (StringUtils.isEmpty(code)) {
            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "用户名");
        }
        if(checkCodeExist(code)){
            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EXIST, "用户名");
        }
        if (StringUtils.isEmpty(telNo)) {
            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "电话号码");
        }
        if (customerUserService.checkMobilePhoneExist(0, telNo)) {
            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EXIST, "电话号码");
        }
        if (StringUtils.isEmpty(password)) {
            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "密码");
        }
        if (!CheckDataUtils.checkPasswordAnySpecCharacter(password)) {
            throw Exceptions.bizException(ErrorCodes.ERROR_CUSTOMER_USER_PASSWORD_FORMAT_ERROR);
        }
        CusCustomer cusCustomer = new CusCustomer();
        cusCustomer.setUserName(userName);
        cusCustomer.setCode(code);
        cusCustomer.setLocked(true);
        cusCustomer.setDeleted(false);
        cusCustomer.setEvaluateLeval(1);
        cusCustomer.setCreator(userName+" "+code);
        cusCustomer.setUserType(3);
        dao.save(getSqlName("insertSelective"), cusCustomer);
        CusUser cusUser = new CusUser();
        cusUser.setIsDeleted(false);
        cusUser.setUserName(code);
        cusUser.setFullName("customer");
        cusUser.setMobilePhone(telNo);
        cusUser.setIsLocked(true);
        cusUser.setIsSystem(true);
        cusUser.setRefCustomerId(cusCustomer.getId());
        String credentialSalt = CredentialUtils.generateSalt();
        cusUser.setCredentialSalt(credentialSalt);
        String encryptionPswd = encryptionProc(password, credentialSalt);
        cusUser.setPassword(encryptionPswd);
        dao.save("CusUserMapper.insertSelective",cusUser);
        Map<String,Object> map = new HashedMap();
        map.put("id",cusCustomer.getId());
        map.put("cususerid",cusUser.getId());

        return map;
    }

    @Override
    public CusEnterpriseInfoDto findEnterpriseInfoById(Integer id) {

        CusEnterpriseInfoDto cusEnterpriseInfoDto = (CusEnterpriseInfoDto) dao.findForObject(getSqlName("searchEnterpriseInfoById"),id);

        if (cusEnterpriseInfoDto != null) {

            SettlementType settlementType = settlementTypeService.findById(cusEnterpriseInfoDto.getRefSettlementId());
            cusEnterpriseInfoDto.setSettlementName(settlementType == null ? "暂无" : settlementType.getName());

            CurrencyDto currencyDto = currencyService.findSingleCurencyByCode(cusEnterpriseInfoDto.getTradingCurrency());
            cusEnterpriseInfoDto.setCurrencyName(currencyDto == null ? "暂无" : currencyDto.getName());

            String comboName = priceComboService.findNameByCode(cusEnterpriseInfoDto.getRefCombos());
            cusEnterpriseInfoDto.setCombosName(comboName == null ? "暂无" : comboName);


            String businessTypeName = businessType2Name(cusEnterpriseInfoDto.getBusinessType(),cusEnterpriseInfoDto.getUserType());
            cusEnterpriseInfoDto.setBusinessTypeValue(businessTypeName);


            List<FileInfoDto> attachments = fileGroupService.getFileDtosByGroupId(cusEnterpriseInfoDto.getLicense());

            cusEnterpriseInfoDto.setFiles(attachments);

            String countryName = areaService.getCountryNameByCode(cusEnterpriseInfoDto.getLocationCountryCode());
            cusEnterpriseInfoDto.setLocationCountryName(countryName == null ? "暂无" : countryName);

            AreaDto areaDto = areaService.findByAreaId(cusEnterpriseInfoDto.getLocationCityCode(), cusEnterpriseInfoDto.getLocationCountryCode());
            cusEnterpriseInfoDto.setLocationCityName(areaDto == null ? "暂无" : areaDto.getName());
        }

        return cusEnterpriseInfoDto;
    }


    @Override
    public CusEnterpriseInfoDto findEnterpriseInfo(){
        CusUser cusUser = customerUserService.findById(PrincipalUtils.getAccountId());
        CusEnterpriseInfoDto cusEnterpriseInfoDto = null;
        if (cusUser != null) {
            cusEnterpriseInfoDto = (CusEnterpriseInfoDto) dao.findForObject(getSqlName("searchEnterpriseInfoById"), cusUser.getRefCustomerId());
        }
        if (cusEnterpriseInfoDto != null) {
            SettlementType settlementType = settlementTypeService.findById(cusEnterpriseInfoDto.getRefSettlementId());
            cusEnterpriseInfoDto.setSettlementName(settlementType == null ? null : settlementType.getName());
            CurrencyDto currencyDto = currencyService.findSingleCurencyByCode(cusEnterpriseInfoDto.getTradingCurrency());
            cusEnterpriseInfoDto.setCurrencyName(currencyDto == null ? null : currencyDto.getName());
            String comboName = priceComboService.findNameByCode(cusEnterpriseInfoDto.getRefCombos());
            cusEnterpriseInfoDto.setCombosName(comboName == null ? null : comboName);
            String businessTypeName = businessType2Name(cusEnterpriseInfoDto.getBusinessType(),cusEnterpriseInfoDto.getUserType());
            cusEnterpriseInfoDto.setBusinessTypeValue(businessTypeName);
            List<FileInfoDto> attachments = fileGroupService.getFileDtosByGroupId(cusEnterpriseInfoDto.getLicense());
            cusEnterpriseInfoDto.setFiles(attachments);
            String countryName = areaService.getCountryNameByCode(cusEnterpriseInfoDto.getLocationCountryCode());
            cusEnterpriseInfoDto.setLocationCountryName(countryName == null ? null : countryName);
            AreaDto areaDto = areaService.findByAreaId(cusEnterpriseInfoDto.getLocationCityCode(), cusEnterpriseInfoDto.getLocationCountryCode());
            cusEnterpriseInfoDto.setLocationCityName(areaDto == null ? null : areaDto.getName());
        }
        return cusEnterpriseInfoDto;
    }

    @Override
    public Boolean checkEmailExist(String email) {

        Boolean isExist = false;

        List<CusCustomer> customerList =  dao.findForList(getSqlName("findByEmail"), email,CusCustomer.class);

        if (customerList != null && customerList.size() > 0) {

            isExist = true;
        } else {

            isExist = false;
        }

        return isExist;
    }

    @Override
    public CusCustomer findCustomerById(Integer id) {
        return (CusCustomer) dao.findForObject(getSqlName("selectByPrimaryKey"), id);
    }


    private void checkDataValid(CusCustomer cusCustomer) {
        if (StringUtils.isEmpty(cusCustomer.getUserName())) {
            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "username");
        }
        if (StringUtils.isEmpty(cusCustomer.getCode())) {
            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "code");
        }
        if (cusCustomer.getRefSettlementId() == 0) {
            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "settlement");
        }
        if (StringUtils.isEmpty(cusCustomer.getTradingCurrency())) {
            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "tradingCurrency");
        }
        if (StringUtils.isEmpty(cusCustomer.getUserType()) || (cusCustomer.getUserType() <  0 || cusCustomer.getUserType() > CustomerConstants.UserType.TRADE )) {
            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "userType");
        }
        if (StringUtils.isEmpty(cusCustomer.getEmail())) {
            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "email");
        }
    }

    private void checkDataValidForUpdate(CusCustomer cusCustomer) {
        if (StringUtils.isEmpty(cusCustomer.getCode())) {
            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "code");
        }
        if (cusCustomer.getRefSettlementId() == 0) {
            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "settlement");
        }
        if (StringUtils.isEmpty(cusCustomer.getTradingCurrency())) {
            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "tradingCurrency");
        }
        if (StringUtils.isEmpty(cusCustomer.getEmail())) {
            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "email");
        }
        if (StringUtils.isEmpty(cusCustomer.getUserType()) || (cusCustomer.getUserType() < 0 || cusCustomer.getUserType() > CustomerConstants.UserType.BOTH )) {
            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "userType");
        }
    }

    private String businessType2Name(String businessTye, Integer userType) {
        Map<String,String> nameMap = new HashedMap();
        if (businessTye == null || "".equals(businessTye)) {
            return "";
        }
        businessTye = businessTye.replace(",", SEPARATOR);
        String[] arrBusinessType = businessTye.split(SEPARATOR);
        StringBuilder businessTypeName = new StringBuilder();
        if (arrBusinessType.length > 0) {
            if (userType != null && userType == CustomerConstants.UserType.LOGISTICS) {
                nameMap = sysDictService.findMapByCatalog(BIZ_SERVICE_TYPE);
            }

            if (userType != null && userType == CustomerConstants.UserType.TRADE) {
                nameMap = sysDictService.findMapByCatalog(BIZ_SERVICE_TRADE_TYPE);
            }

            for (String code : arrBusinessType) {
                String name = nameMap.get(code);
                if (name != null && name.length() > 0) {
                    businessTypeName.append(name);
                    businessTypeName.append(SEPARATOR);
                }
            }
            if (businessTypeName.length() > 0) {
                businessTypeName.deleteCharAt(businessTypeName.length() - 1);
            }
        }
        return businessTypeName.toString();
    }

    private String encryptionProc(String pswd, String credentialSalt) {
        return new Md5Hash(pswd, credentialSalt).toString();
    }


    @Override
    protected String getMapperNamespace() {
        return "CusCustomerMapper";
    }

    private static final String BIZ_SERVICE_TYPE = "biz.service.type";

    private static final String BIZ_SERVICE_TRADE_TYPE = "biz.service.trade.type";

    @Override
    public void setCustomerAuthStatus(int customerId, int state) {
        Map<String,Object> map = new HashMap<>();
        map.put("id",customerId);
        map.put("status", state);
        dao.update("CusCustomerMapper.updateStatus",map);
    }

    @Override
    public void createPayAccount(CusCustomer cusCustomer,CusCompanyDto cusCompanyDto){
        Account payAccount = new Account();
        payAccount.setCustName(cusCustomer.getCode());
        payAccount.setNickName(cusCustomer.getUserName());
        //payAccount.setAccountType(PayConstant.AccountType.LOGISTICS_SYS);
        payAccount.setAccountType(cusCustomer.getUserType());
        String accountId = NOGenerator.getAccountNo(payAccount.getAccountType());
        payAccount.setId(accountId);
        payAccount.setCustomerId(cusCustomer.getId());
        payAccount.setEmail(cusCustomer.getEmail());
        payAccount.setMobilePhone(cusCompanyDto.getTelNo());
        payAccount.setIdType(CertificateType.UNIFIED_SOCIAL_CREDIT_CODE);
        payAccount.setIdCode(cusCompanyDto.getTaxCode());
        payAccount.setIsDeleted(false);
        payAccount.setCustProperty("00");
        try{
            payAccount.setCreateUserId(PrincipalUtils.getAccountId());
        }catch (Exception e){
            payAccount.setCreateUserId(0);
        }

        ThirdPayAccount thirdPayAccount = new ThirdPayAccount();
        thirdPayAccount.setId(UUIDGenerator.generateRandomUUID());
        thirdPayAccount.setAccountId(accountId);
        thirdPayAccount.setThirdPayId(UUIDGenerator.generateRandomUUID());
        thirdPayAccount.setIsDeleted(false);
        thirdPayAccount.setCurrency(cusCustomer.getTradingCurrency());
        thirdPayAccount.setThirdType(PayConstant.PaymentType.SYSTEM);
        accountService.save(payAccount);
        thirdPayAccountService.insert(thirdPayAccount);
    }

    /**
     * 查询账户ID为NULL的客户
     * @return
     */
    @Override
    public List<CusCustomer> findCustomers() {
        List<CusCustomer> cusCustomers = dao.findForList(getSqlName("findCustomers"),CusCustomer.class);
        return cusCustomers;

    }

    /**
     * 查询创建时间内的客户数量
     *
     * @param dateBegin
     * @param dateEnd
     * @return
     */
    @Override
    public List<CusCustomer> finByCreateTimeForRpt(Date dateBegin, Date dateEnd) {
        Map<String,Object> map = new HashMap<>(16);
        map.put("dateBegin",dateBegin);
        map.put("dateEnd", dateEnd);
        return dao.findForList(getSqlName("finByCreateTimeForRpt"),map,CusCustomer.class);
    }
}
